﻿/*jslint  browser: true, white: true, plusplus: true */
/*global $, countries */

$(function () {
    'use strict';
    var index_source_factory=-1;
    var countriesArray = $.map(countries, function (value, key) { 
        index_source_factory++;
        //console.info("index_source_factory:"+index_source_factory);
        return { value: value, data: key ,myhref:"../table_source_factory.html",class:"left_source_factory_content_"+index_source_factory}; 
    });
    //console.info(countriesArray);
    // Setup jQuery ajax mock:
   /* $.mockjax({
        url: '*',
        responseTime: 2000,
        response: function (settings) {
            var query = settings.data.query,
                queryLowerCase = query.toLowerCase(),
                re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
                suggestions = $.grep(countriesArray, function (country) {
                     // return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
                    return re.test(country.value);
                }),
                response = {
                    query: query,
                    suggestions: suggestions
                };

            this.responseText = JSON.stringify(response);
        }
    });*/

    // Initialize ajax autocomplete:
    /*$('#autocomplete-ajax').autocomplete({
        // serviceUrl: '/autosuggest/service/url',
        lookup: countriesArray,
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

    var nhlTeams = ['Anaheim Ducks', 'Atlanta Thrashers', 'Boston Bruins', 'Buffalo Sabres', 'Calgary Flames', 'Carolina Hurricanes', 'Chicago Blackhawks', 'Colorado Avalanche', 'Columbus Blue Jackets', 'Dallas Stars', 'Detroit Red Wings', 'Edmonton OIlers', 'Florida Panthers', 'Los Angeles Kings', 'Minnesota Wild', 'Montreal Canadiens', 'Nashville Predators', 'New Jersey Devils', 'New Rork Islanders', 'New York Rangers', 'Ottawa Senators', 'Philadelphia Flyers', 'Phoenix Coyotes', 'Pittsburgh Penguins', 'Saint Louis Blues', 'San Jose Sharks', 'Tampa Bay Lightning', 'Toronto Maple Leafs', 'Vancouver Canucks', 'Washington Capitals'];
    var nbaTeams = ['Atlanta Hawks', 'Boston Celtics', 'Charlotte Bobcats', 'Chicago Bulls', 'Cleveland Cavaliers', 'Dallas Mavericks', 'Denver Nuggets', 'Detroit Pistons', 'Golden State Warriors', 'Houston Rockets', 'Indiana Pacers', 'LA Clippers', 'LA Lakers', 'Memphis Grizzlies', 'Miami Heat', 'Milwaukee Bucks', 'Minnesota Timberwolves', 'New Jersey Nets', 'New Orleans Hornets', 'New York Knicks', 'Oklahoma City Thunder', 'Orlando Magic', 'Philadelphia Sixers', 'Phoenix Suns', 'Portland Trail Blazers', 'Sacramento Kings', 'San Antonio Spurs', 'Toronto Raptors', 'Utah Jazz', 'Washington Wizards'];
    var nhl = $.map(nhlTeams, function (team) { return { value: team, data: { category: 'NHL' }}; });
    var nba = $.map(nbaTeams, function (team) { return { value: team, data: { category: 'NBA' } }; });
    var teams = nhl.concat(nba);

    // Initialize autocomplete with local lookup:
    $('#autocomplete').devbridgeAutocomplete({
        lookup: teams,
        minChars: 1,
        onSelect: function (suggestion) {
            $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data.category);
        },
        showNoSuggestionNotice: true,
        noSuggestionNotice: 'Sorry, no matching results',
        groupBy: 'category'
    });
    
    // Initialize autocomplete with custom appendTo:
    $('#autocomplete-custom-append').autocomplete({
        lookup: countriesArray,
        appendTo: '#suggestions-container'
    });*/

    // Initialize autocomplete with custom appendTo:
    $('#autocomplete-dynamic').autocomplete(/*"url",*/{
        lookup: countriesArray,//本地数组
        //serviceUrl:"/action.do",
        //dataType: "json",//数据格式      
        /*params : {
           // 传递参数方式               
            action:,
            s: 
        },*/
        appendTo: '#suggestions-container',
        minChars: 1,//至少输入的字符数，default：1
        max: 10,    //下拉项目的个数，default：10
        maxHeight:200, 
        scrollHeight: 200,// 下拉框的高度， Default: 180
        scroll: true,//当结果集大于默认高度时，是否使用滚动条，Default: true
        multiple: false,//是否允许输入多个值. Default: false
        autoFill: true,// 是否自动填充. Default: false
        mustMatch:true,//如果设置为true,只会允许匹配的结果出现在输入框,当用户输入的是非法字符时,将被清除， Default: false
        /*"suggestions": [  
                    { "value": "United Arab Emirates", "data": "AE" },  
                    { "value": "United Kingdom",       "data": "UK" },  
                    { "value": "United States",        "data": "US" }  
                ]  */
        onSelect: function (suggestion) {
            console.info(suggestion);
            //添加到.right
            var rignthContentTop=$(this).offset().top-100+"px";
            var ringthContentleft=$(this).offset().left+"px";
            console.info($(window.parent.document).find(".right"));
            //  4==left id前缀
            //console.info($("#draggable" + $(this).attr('id').substr(4)));
            //autocomplete 存在iframe
            $(window.parent.document).find(".right").append('<div class="draggable" id="draggable' + suggestion.class.substr(4) + 
            //'"  style=" background:' + getRandomColor() + '">\n' +
            '"  style="border:1px solid black;background: white ;top:'+rignthContentTop+'">\n' +
                //'            <h4>' + $(this).text() + '</h4>\n' +
                '            <p class="lt" style="z-index:1000"></p>\n' +
                '            <p class="wh" style="z-index:1000"></p>\n' +
                '            <p class="close" style="z-index:1000" >关闭</p>\n' +
                '            <div id="right'+suggestion.class.substr(4)+'" style="width: 100%px;height: 100%;overflow:auto;"></div>'+
                '        </div>')
            //console.info($(this));
            //加载页面
            $(window.parent.document).find("#right"+suggestion.class.substr(4)).load(suggestion.myhref);
            //左列表选项隐藏或禁用 autocomplete 不需要禁用        
            //$(this).parent().hide();
            //初始banding事件 避免初始化无法关闭问题
            $(window.parent.document).find(".close").click(function () {
                //左列表选项显示或启用  9 == draggable 
                //autocomplete 左侧无
                //$('.left').find($('#left' + $(this).parent().attr('id').substr(9)).parent()).show();
                $(this).parent().remove();

                //非必要时不采用
                //$('.right').find("#"+$(this).parent().attr("id")).remove();

                //防止其他js破坏 尽可能在right内部使用。尽可能少使用在body中
                $("#content").nextAll().remove();
            })
            //删除dialog 自动触发模式
            $($(window.parent.document).find(".dialog-box-close")).click();
        },
        showNoSuggestionNotice: true,
        noSuggestionNotice: '<span style="color:red">抱歉,输入的不匹配，请重新输入</span>'
    });
    //console.info($('#autocomplete-dynamic'));
});